package org.tuoren.official.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.tuoren.common.core.domain.R;
import org.tuoren.common.core.utils.StringUtils;
import org.tuoren.common.core.utils.file.MimeTypeUtils;
import org.tuoren.common.log.annotation.Log;
import org.tuoren.common.log.enums.BusinessType;
import org.tuoren.common.web.core.BaseController;
import org.tuoren.official.constant.ConstantUtils;
import org.tuoren.official.service.IOssService;
import org.tuoren.official.util.EncodingUtil;
import org.tuoren.official.util.RsaUtil;
import org.tuoren.system.domain.vo.SysOssUploadVo;
import org.tuoren.system.domain.vo.SysOssVo;
import org.tuoren.system.service.ISysOssService;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/oss")
@Slf4j
public class OssController extends BaseController {

    private final IOssService ossService;
    private final ISysOssService sysOssService;
    @Value("${oss.key.image}")
    String ossImageKey;
    @Value("${oss.key.file}")
    String ossFileKey;

    /**
     * 上传图片
     *
     * @param file 文件
     */
    @SaCheckPermission("internal:oss:upload")
    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/uploadImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<SysOssUploadVo> uploadImage(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        String extension = FileUtil.extName(file.getOriginalFilename());
        if (!(StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)|| StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.VIDEO_EXTENSION))) {
            return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
        }
        SysOssVo oss = ossService.upload(ossImageKey, file);
        SysOssUploadVo uploadVo = new SysOssUploadVo();
        uploadVo.setUrl(oss.getUrl());
        uploadVo.setFileName(oss.getOriginalName());
        uploadVo.setOssId(oss.getOssId().toString());
        uploadVo.setFilePath(oss.getFileName());
        return R.ok(uploadVo);
    }

    /**
     * 上传文件
     *
     * @param file 文件
     */
    @SaCheckPermission("internal:oss:upload")
    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<SysOssUploadVo> uploadFile(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = ossService.upload(ossFileKey, file);
        SysOssUploadVo uploadVo = new SysOssUploadVo();
        uploadVo.setUrl(oss.getUrl());
        uploadVo.setFileName(oss.getOriginalName());
        uploadVo.setOssId(oss.getOssId().toString());
        uploadVo.setFilePath(oss.getFileName());
        return R.ok(uploadVo);
    }
    /**
     * 下载文件
     */
    @SaCheckPermission("internal:oss:upload")
    @GetMapping("/download/{ossId}")
    public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
        sysOssService.download(ossId, response);
    }
    /**
     * 文件预览
     *
     * @param fileUrl
     * @return
     */
    @GetMapping("/filePreview")
    @SaCheckPermission("internal:oss:upload")
    public R filePreview(String fileUrl) {
        try {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(fileUrl) && !fileUrl.contains(ConstantUtils.HTTP)) {
                fileUrl = ConstantUtils.FASTDFS_PATH + fileUrl;
            }
            //加密
            fileUrl = RsaUtil.encrypt(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件预览加密异常：{}", e);
        }
        fileUrl = EncodingUtil.encodeURIComponent(fileUrl);
        Map<String, String> newMap = new HashMap<>();
        newMap.put("filePath", ConstantUtils.FILE_PREVIEW + fileUrl);
        return R.ok(newMap);
    }

}
